package lumis.portal.presentation.perspective.admin;

import lumis.portal.PortalException;
import lumis.portal.PortalStringResource;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.channel.ChannelConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.manager.ManagerFactoryInternal;
import lumis.portal.page.PageConfig;
import lumis.portal.page.PageWebResource;
import lumis.portal.presentation.PortalModeUtil;
import lumis.portal.presentation.core.HTMLFragmentComponent;
import lumis.portal.presentation.core.LayoutFilePage;
import lumis.portal.presentation.perspective.IPortalMode;
import lumis.portal.presentation.perspective.IPortalModeSPI;
import lumis.portal.presentation.perspective.Perspective;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.portal.user.UserConfig;
import lumis.util.CookieUtil;
import lumis.util.IResource;
import lumis.util.security.acl.IPermission;

import java.text.MessageFormat;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.protocol.http.WebRequest;

/**
 * Renders Portal Studio header HTML fragment.
 *
 * @version $Revision: 13321 $ $Date: 2011-08-08 11:32:13 -0300 (Mon, 08 Aug 2011) $
 * @since 6.0.0
 */
@SuppressWarnings("serial")
public class PortalStudioHeaderPanel extends Panel
{
	/**
	 * Component used to setup about popup link. 
	 *
	 * @version $Revision: 13321 $ $Date: 2011-08-08 11:32:13 -0300 (Mon, 08 Aug 2011) $
	 * @since 6.0.0
	 */
	private class LumisAbout extends WebMarkupContainer
	{
		/**
		 * The identifier of the channel from the the about link was clicked.
		 * @since 6.0.0
		 */
		private final String channelId;

		public LumisAbout(String id, String channelId) 
		{
			super(id);
			this.channelId = channelId;
		}

		@Override
		protected void onComponentTag(ComponentTag tag) 
		{
			super.onComponentTag(tag);
			
			tag.put("onclick", "javascript:window.open('main.jsp?lumChannelId="+channelId+"&amp;lumPageId=LumisBlankPage&amp;lumRTI=lumis.service.portalmanagement.build.buildInformation','_blank', 'width=379,height=352','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no')");
		}
	}	

	/**
	 * Component used to render the perspectives of the Portal.
	 *
	 * @version $Revision: 13321 $ $Date: 2011-08-08 11:32:13 -0300 (Mon, 08 Aug 2011) $
	 * @since 6.0.0
	 */
	private class PerspectiveSelectionComponent extends HTMLFragmentComponent
	{
		int lumLastMode = 0;
		public PerspectiveSelectionComponent(String id) 
		{
			super(id, false);
		}

		@Override
		protected CharSequence getHTMLFragment(MarkupStream markupStream, ComponentTag openTag) 
		{
			final IResource RESOURCE = new PortalStringResource();
			RESOURCE.addResourcePath("/lumis/portal/strings/strings");
			MessageFormat LIST_LAYOUT;
			
			try 
			{
				LIST_LAYOUT = new MessageFormat("<ul class=\"menu_modeswap\"><li><a href=\"#\" title=\""+ ManagerFactory.getLocalizationManager().localize("STR_CHANGE_PERSPECTIVE", RESOURCE) + "\">{0}<img src=\"lumis/portalstudio/client/images/ico_ddarrow.png\" class=\"ddarrow\" alt=\" \"/></a><ul class=\"dd\">{1}</ul></li></ul>");
				final MessageFormat LIST_ITEM = new MessageFormat("<li><a href=\"{0}\" {2}>{1}</a></li>");
				final MessageFormat LIST_ITEM_DISABLE = new MessageFormat("<li><a href=\"{0}\" onclick=\"return false\" {2}><span style=\"color:#c0c0c0 !important;cursor:default !important;\">{1}</span></a></li>");	
		
				StringBuffer buffer = new StringBuffer();
				
				HttpServletRequest httpServletRequest = ((WebRequest) getRequest()).getHttpServletRequest();
				IPortalMode currentPortalMode = PortalModeUtil.getPortalMode(httpServletRequest);
				
				PageWebResource pageWebResource = ((LayoutFilePage)getPage()).getPageWebResource();
				PageConfig pageConfig = pageWebResource.getPage();
				
				//Gets the actual mode before the changing of perspective is complete, so when the process is complete we can use it as the last mode.
				String lastMode = CookieUtil.getCookie(httpServletRequest, "lumMode");
				
				if(lastMode != null)
				{
					lumLastMode = Integer.parseInt(lastMode);
				}

				Perspective[] values = Perspective.values();
				for (int perspectiveIterator = 0; perspectiveIterator < values.length; perspectiveIterator++)
				{
					Perspective perspective = values[perspectiveIterator];
					if(perspective.value() != currentPortalMode.getPerspective().value())
					{
						String localizedName = ManagerFactory.getLocalizationManager().localize(perspective.getName(), new PortalStringResource(), SessionConfig.getCurrentSessionConfig().getLocale());
						
						Set<IPortalMode> modes = perspective.getModes();
						//runs for all modes available for that perspective
						
						boolean hasPermission = true;
						boolean found = false;
						String link = null;
						for (IPortalMode iPortalMode : modes)
						{
							if (iPortalMode.getId() == lumLastMode && lumLastMode != IPortalMode.MODE_VIEW)
							{
								link = "javascript:LumisPortal.openMode('"+ lumLastMode +"');";
								found = true;
							}
							else if (!found)
							{
								link = "javascript:LumisPortal.openPerspective('"+ perspective.value() +"');";
							}
							
							IPermission permission = ((IPortalModeSPI)iPortalMode).getPermissionProvider().getPermission();
							LayoutFilePage layoutFilePage = (LayoutFilePage)getPage();
							String rootChannelId = layoutFilePage.getRootChannelId();
							//if a channel is selected or the user has no permissions over the perspective or the user is in a admin channel, disables the link to change perspective.
							String pageId = pageConfig.getId();
							if(PageConfig.PAGE_ID_ADMIN_SERVICES.equals(pageId) // if user is viewing the services
								|| PageConfig.PAGE_ID_ADMIN_PAGE_TEMPLATES.equals(pageConfig.getId())  // if user is viewing page templates
								|| PageConfig.PAGE_ID_ADMIN_CHANNEL_TEMPLATES.equals(pageConfig.getId()) //if user is channel templates
								|| PageConfig.PAGE_ID_ADMIN_SUBCHANNELS.equals(pageConfig.getId()) //if user is admin channels
								|| PageConfig.PAGE_ID_ADMIN_PAGES.equals(pageConfig.getId()) // if  user is viewing added pages
								|| rootChannelId.equals(ChannelConfig.LUMIS_ADMIN_CHANNEL_ID) // if  user is viewing modules, content management or configurations
								|| !(ManagerFactoryInternal.getPageAclManager().checkPermission(
										SessionConfig.getCurrentSessionConfig(), pageConfig.getId(), permission, PortalTransactionFactory.getCurrentTransaction()))) // checks all modes if the user has permissions for at least one, if not, disables the perspective
							{		
								hasPermission = false;
							}		
						}
						
						if (hasPermission)
						{
							buffer.append(LIST_ITEM.format(new Object[]{link,localizedName}));
						}
						else
						{
							buffer.append(LIST_ITEM_DISABLE.format(new Object[]{link,localizedName}));
						}
					}				
				}
				return LIST_LAYOUT.format(
						new Object[]{
								ManagerFactory.getLocalizationManager().localize(currentPortalMode.getPerspective().getName(), 
										new PortalStringResource(), SessionConfig.getCurrentSessionConfig().getLocale()), buffer.toString()}
					);
			} 
			catch (PortalException e) 
			{
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * Component used to render the PortalModes.
	 * @version $Revision: 13321 $ $Date: 2011-08-08 11:32:13 -0300 (Mon, 08 Aug 2011) $
	 * @since 6.0.0
	 */
	private class ModeSelectionComponent extends HTMLFragmentComponent
	{
		/**
		 * @since 6.0.0
		 */
		static final String MODE_SELECTED = "class=\"selected\"";
		final MessageFormat LIST_LAYOUT = new MessageFormat("<ul class=\"menu_modeoptions\">{0}</ul>");
		final MessageFormat LIST_ITEM = new MessageFormat("<li id=\"lumbarModeLink1\"><a href=\"{1};\" title=\"{0}\" {2} >{0}</a></li>");
		final MessageFormat LIST_ITEM_DISABLED = new MessageFormat("<li id=\"lumbarModeLink1\"><a href=\"{1}\" onclick=\"return false\" title=\"{0}\" {2} ><span style=\"color:#c0c0c0 !important;cursor:default !important;\">{0}</span></a></li>");

		public ModeSelectionComponent(String id) 
		{
			super(id, false);
		}

		@Override
		protected CharSequence getHTMLFragment(MarkupStream markupStream, ComponentTag openTag) 
		{
			
			try 
			{					
				StringBuffer buffer = new StringBuffer();

				PageWebResource pageWebResource = ((LayoutFilePage)getPage()).getPageWebResource();
				PageConfig pageConfig = pageWebResource.getPage();
				
				HttpServletRequest httpServletRequest = ((WebRequest) getRequest()).getHttpServletRequest();
				IPortalMode currentPortalMode = PortalModeUtil.getPortalMode(httpServletRequest);
				Perspective perspective = currentPortalMode.getPerspective();
				Set<IPortalMode> modes = perspective.getModes();
				for (IPortalMode iPortalMode : modes)
				{	
					String htmlClass = (currentPortalMode.getId() != iPortalMode.getId())?"":MODE_SELECTED;
					
					String localizedName = ManagerFactory.getLocalizationManager().localize(iPortalMode.getName(), new PortalStringResource(), SessionConfig.getCurrentSessionConfig().getLocale());
					IPermission currentPermission = ((IPortalModeSPI)iPortalMode).getPermissionProvider().getPermission();
					LayoutFilePage layoutFilePage = (LayoutFilePage)getPage();
					String rootChannelId = layoutFilePage.getRootChannelId();
					
					if (!ManagerFactoryInternal.getPageAclManager().checkPermission(SessionConfig.getCurrentSessionConfig(), pageConfig.getId(), currentPermission, PortalTransactionFactory.getCurrentTransaction())
							|| rootChannelId.equals(ChannelConfig.LUMIS_ADMIN_CHANNEL_ID))
					{
						buffer.append(LIST_ITEM_DISABLED.format(new Object[]{localizedName,"javascript:LumisPortal.openMode('"+ iPortalMode.getId() +"')", htmlClass}));
					}
					else
					{
						buffer.append(LIST_ITEM.format(new Object[]{localizedName,"javascript:LumisPortal.openMode('"+ iPortalMode.getId() +"')", htmlClass}));
					}
				}
				
				return LIST_LAYOUT.format(new Object[]{buffer.toString()});
			} 
			catch (PortalException e) 
			{
				throw new RuntimeException(e);
			}
		}
	}
	
	/**
	 * Component used to render the User menu.
	 * @version $Revision: 13321 $ $Date: 2011-08-08 11:32:13 -0300 (Mon, 08 Aug 2011) $
	 * @since 6.0.0
	 */
	private class UserSelectionComponent extends HTMLFragmentComponent
	{
		final MessageFormat LIST_LOGOUT = new MessageFormat("<ul class=\"menu_dd\"><li><a href=\"#\">{0}<img src=\"lumis/portalstudio/client/images/ico_ddarrow.png\" class=\"ddarrow\" alt=\"STR_USER_OPTIONS\" /></a><ul class=\"dd\"><li><a href=\"login.jsp?action=logout\">{1}</a></li></ul></li></ul>");
		StringBuffer buffer = new StringBuffer();
		
		public UserSelectionComponent(String id) 
		{
			super(id, false);
		}

		@Override
		protected CharSequence getHTMLFragment(MarkupStream markupStream, ComponentTag openTag) 
		{
			try 
			{
				String localizedName = ManagerFactory.getLocalizationManager().localize("STR_LOGOUT", new PortalStringResource(), SessionConfig.getCurrentSessionConfig().getLocale());
				SessionConfig sessionConfig = SessionConfig.getCurrentSessionConfig();
				UserConfig userConfig = ManagerFactory.getUserManager().get(sessionConfig, sessionConfig.getUserId(), PortalTransactionFactory.getCurrentTransaction());
				
				String shownName = null;
				String lastName = userConfig.getLastName();
				if (lastName != null)
				{
					shownName = userConfig.getFirstName()+" "+ userConfig.getLastName();
				}
				else
				{
					shownName = userConfig.getFirstName();
				}
				
				if (shownName.length() > 20)
				{
					shownName = shownName.substring(0,20).concat("...");
				}
				
				return buffer.append(LIST_LOGOUT.format(new Object[]{shownName, localizedName}).toString());
			} 
			catch (Exception e) 
			{
				throw new RuntimeException(e);
			}
		}
	}
	
	/**
	 * Class constructor
	 * @param id panel identifier
	 * @since 6.0.0
	 */
	public PortalStudioHeaderPanel(String id)
	{
		super(id);
	}
	
	@Override
	protected void onBeforeRender()
	{
		super.onBeforeRender();
		try 
		{			
			LayoutFilePage page = (LayoutFilePage)getPage();
			String channelId = page.getPageWebResource().getPage().getChannelId();
			add(new LumisAbout("LumisAbout", channelId));
			add(new PerspectiveSelectionComponent("LumisPerspective"));
			add(new ModeSelectionComponent("LumisModes"));
			add(new UserSelectionComponent("UserName"));
		} 
		catch (Exception e) 
		{
			throw new RuntimeException(e);
		}
	}
}
